package www.dianbaozu.com.ui.server

import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.lxj.xpopup.core.BasePopupView
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentInviteJoiningServerBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.data.entities.InviteesServerEntity
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.data.entities.ViewPagePosition
import www.wen.com.common.lib.extension.observeObject
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.ResultUiCallBack
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter


/**
 * @author WEN
 * @Description:通过邀请码或者链接加入服务器
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class InviteJoiningServerFragment : BaseLoadingFragment<FragmentInviteJoiningServerBinding>(), View.OnClickListener {

    private val mBaseApiViewModel: InviteJoiningServerViewModel by viewModels()

    override val viewModel: InviteJoiningServerViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            tilte = getString(R.string.joining_the_server),
            action = ::titleAction
    )

    override fun getLayoutId(): Int = R.layout.fragment_invite_joining_server

    override fun lazyInitView() {
        dataBinding.viewModel = mBaseApiViewModel
        joinServer()
        observeListen()
    }

    private fun observeListen() {
        observeObject(KeyHelper.INVITE_JOINING_KEY, this, String::class.java) {
            if (this.isNotBlank()) {
                dataBinding.etInputServerName.setText(this)
                dataBinding.tvCreateServer.performClick()
            }
        }
    }

    private fun joinServer() {
        val url = arguments?.getString(BUNDLE_DATA, "") ?: ""
        if (url.isNotBlank()) {
            dataBinding.etInputServerName.setText(url)
            dataBinding.tvCreateServer.performClick()
        }
    }

    override fun onClick(v: View) {
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                tipSuccess = "",
                isShowToastTip = true,
                request = { appDataManage ->
                    appDataManage.requestShareFind(
                            RequestBodyParameter(
                                    shareUrl = dataBinding.etInputServerName.text.toString()
                            ))
                }
        ) {
            showInvitePopupView(InviteesServerEntity(
                    nickName = if (it.server.serverMember != null) it.server.serverMember!!.nickName else it.inviteUser.nickName,
                    serverLogo = it.server.serverLogo,
                    serverName = it.server.serverName,
                    serverIntro = it.server.serverIntro,
                    joined = it.server.serverMember != null,
            )) { _: View, inviteesServerEntity: InviteesServerEntity, basePopupView: BasePopupView ->
                when (inviteesServerEntity.joined) {
                    true -> {
                        basePopupView.dismiss()
                        postObject(KeyHelper.REFRESHING_SERVER_LIST, true)
                        postObject(KeyHelper.MAIN_VIEWPAGER_POSITION_KEY, ViewPagePosition(0))
                        findNavController().popBackStack(R.id.mainFragment, false)
                    }
                    else -> {
                        mBaseApiViewModel.requestUniversally(
                                viewModelScope = lifecycleScope,
                                tipLoading = getString(R.string.com_joining_server),
                                tipFail = getString(R.string.failed_added),
                                tipSuccess = "",
                                isShowToastTip = true,
                                request = { appDataManage ->
                                    appDataManage.requestMemberInvite(
                                            RequestBodyParameter(
                                                    serverId = it.server.serverId,
                                                    userId = it.inviteUser.id,
                                            ))
                                }
                        ) {
                            toast("加入服务器成功")
                            basePopupView.dismiss()
                            postObject(KeyHelper.REFRESHING_SERVER_LIST, true)
                            postObject(KeyHelper.MAIN_VIEWPAGER_POSITION_KEY, ViewPagePosition(0))
                            findNavController().popBackStack(R.id.mainFragment, false)
                        }
                    }
                }
            }
        }
    }

    private fun showInvitePopupView(invitees: InviteesServerEntity, result: ResultUiCallBack<InviteesServerEntity>) {
        CreateXPopupHelper.createBottomJoinServerPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            inviteesEntity = invitees
            resultCallBackInvitees = result
        })
    }

}



